import { createRouter, createWebHashHistory } from "vue-router";
import Admin from "../lagouts/admin.vue";
import Index from "../pages/index.vue";
import About from "../pages/about.vue";
import NotFound from "../pages/404.vue";
import Login from "../pages/login.vue";
import GoodList from "../pages/goods/list.vue";
import CategoryList from "../pages/category/list.vue";

import Form from "../demo/form.vue";
import Cookie from "../demo/useVueCookie.vue";
import zhiling from "../demo/vue2/zhiling.vue";
import myHeader from "../demo/vue2/todo-list/myHeader.vue";
import Collaps from "../demo/collaps.vue";

const routes = [
  {
    path: "/",
    component: Admin,
    // 子路由
    children: [
      {
        path: "/",
        component: Index,
        meta: {
          title: "后台首页",
        },
      },
    ],
  },
  {
    path: "/about",
    component: About,
  },
  {
    path: "/login",
    component: Login,
    meta: {
      title: "登录页面",
    },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: NotFound,
  },
  {
    path: "/form",
    component: Form,
  },
  {
    path: "/cookie",
    component: Cookie,
  },
  {
    path: "/zhiling",
    component: zhiling,
  },
  {
    path: "/todo",
    component: myHeader,
  },
  { path: "/collaps", component: Collaps },
];
//动态路由，用于匹配菜单动态添加路由
const asyncRoutes = [
  {
    path: "/",
    name: "/",
    component: Index,
    meta: {
      title: "后台首页",
    },
  },
  {
    path: "/goods/list",
    name: "/goods/list",
    component: GoodList,
    meta: {
      title: "商品管理",
    },
  },
  {
    path: "/category/list",
    name: "/category/list",
    component: CategoryList,
    meta: {
      title: "分类列表",
    },
  },
];
export const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//动态添加路由的方法
export function addRoutes(menus) {
  //是否有新的路由
  let hasNewRoutes = false;
  let fndAndAddRoutesByMenus = (arr) => {
    arr.forEach((e) => {
      let item = asyncRoutes.find((o) => o.path == e.frontpath);
      if (item && !router.hasRoute(item.path)) {
        router.addRoute("admin", item);
        hasNewRoutes = true;
      }
      if (e.child && e.child.length > 0) {
        fndAndAddRoutesByMenus = e.child;
      }
    });
  };
  fndAndAddRoutesByMenus(menus);
  return hasNewRoutes;
}
